//
//  ChatBaViewController.m
//  聊吧
//
//  Created by 刘洋 on 16/6/13.
//  Copyright © 2016年 刘洋. All rights reserved.
//

#import "ChatBaViewController.h"
#import "LoginAndRegisterViewController.h"
#import "ChattingViewController.h"
#import "ChatBaTableViewCell.h"
#import "AppDelegate.h"
@interface ChatBaViewController ()<EMChatManagerDelegate,UITableViewDataSource,UITableViewDelegate,EMDeviceManagerNetworkDelegate>


@property(nonatomic,retain)BaseTableView *conversationTableView;

@property(nonatomic,retain)NSMutableArray *conversationArray;

@property(nonatomic,retain)NSMutableArray *messageArray;

@property(nonatomic,assign)NSUInteger unreadCounts;


@end

@implementation ChatBaViewController


-(void)dealloc{
    [_conversationTableView release];
    [_conversationArray release];
    [super dealloc];
    
}



-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.conversationTableView headerBeginRefreshing];
    
    
    
    
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:dispatch_get_main_queue()];
    
/*
//从环信数据库获取会话列表
    NSArray *conversationsDB = [[EaseMob sharedInstance].chatManager loadAllConversationsFromDatabaseWithAppend2Chat:YES];
    
    
    self.conversationArray = [NSMutableArray arrayWithArray:conversationsDB];

//计算出所有未读消息
     self.unreadCounts = 0;
    for (EMConversation *conver in self.conversationArray) {
        
        NSUInteger  count = conver.unreadMessagesCount;
        self.unreadCounts = self.unreadCounts + count;
        
    }
    NSLog(@"\\\\\\\\\\\\\\\\%ld",self.unreadCounts);
    
//给tabbar发送消息
    NSString *unread = [NSString stringWithFormat:@"%ld",self.unreadCounts];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"unreadBadge" object:unread];
 */
    [self.conversationTableView addHeaderWithCallback:^{
        
        //从环信数据库获取会话列表
        NSArray *conversationsDB = [[EaseMob sharedInstance].chatManager loadAllConversationsFromDatabaseWithAppend2Chat:YES];
        
        
        self.conversationArray = [NSMutableArray arrayWithArray:conversationsDB];
        
        //计算出所有未读消息
        self.unreadCounts = 0;
        for (EMConversation *conver in self.conversationArray) {
            
            NSUInteger  count = conver.unreadMessagesCount;
            self.unreadCounts = self.unreadCounts + count;
            
        }
        NSLog(@"\\\\\\\\\\\\\\\\%ld",self.unreadCounts);
        
        //给tabbar发送消息
        NSString *unread = [NSString stringWithFormat:@"%ld",self.unreadCounts];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"unreadBadge" object:unread];

        
        
        [self.conversationTableView reloadData];
        
        NSLog(@"wwwwwwww");
        [self.conversationTableView headerEndRefreshing];
        
    }];
    
   
   

    
}




- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.messageArray = [NSMutableArray array];
   
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"聊吧";
    NSLog(@"这是聊吧页面");
    
    
    self.conversationTableView = [[BaseTableView alloc]initWithFrame:CGRectMake(0, 0, ROOTWIDTH, ROOTHEIGHT - tabBarHeight - naVCHeight) style:UITableViewStylePlain];
    
    self.conversationTableView.backgroundColor = [UIColor whiteColor];
    self.conversationTableView.delegate = self;
    self.conversationTableView.dataSource = self;
    [self.view addSubview:self.conversationTableView];
    [_conversationTableView release];
    
    self.conversationTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.conversationTableView registerClass:[ChatBaTableViewCell class] forCellReuseIdentifier:@"reuse"];
    


    [self.conversationTableView addHeaderWithCallback:^{
        
        [self.conversationTableView reloadData];
        
        NSLog(@"111111111");
         [self.conversationTableView headerEndRefreshing];
        
    }];
    
   
    
    
    
  
    
    // Do any additional setup after loading the view.
}




-(void)didReceiveMessage:(EMMessage *)message
{
    

//获取所有接收到的消息
    [self.messageArray addObject:message];
    
//遍历出所有消息的发送来源
    NSMutableArray *nameArr = [NSMutableArray array];
    for (EMMessage *message in self.messageArray) {
        [nameArr addObject:message.from];
        
    }
    NSLog(@"%@",nameArr);
    

//找到当前会话列表中所有会话者的账号
    NSMutableArray *chatterArray = [NSMutableArray array];
    for (EMConversation *cover in self.conversationArray) {
        [chatterArray  addObject:cover.chatter];
    }
    
//判断发送来的消息是否已经是存在在列表中
    if ([chatterArray containsObject:message.from]) {
        
       //存在,不执行
        
    }else{
        
       //不存在,创建该消息的会话
        
        EMConversation *newConver = [[EaseMob sharedInstance].chatManager conversationForChatter:message.from conversationType:eConversationTypeChat];
  //这是未读变更
         newConver.enableUnreadMessagesCountEvent = YES;
  //将所有消息设为未读
         [newConver markAllMessagesAsRead:NO];
   //存入环信数据库
        [[EaseMob sharedInstance].chatManager insertConversationToDB:newConver append2Chat:YES];
      
        
        NSArray *conversationsDB = [[EaseMob sharedInstance].chatManager loadAllConversationsFromDatabaseWithAppend2Chat:YES];
    
        
        self.conversationArray = [NSMutableArray arrayWithArray:conversationsDB];
        
    
    }
 //计算未读消息个数
    self.unreadCounts = 0;
    for (EMConversation *conver in self.conversationArray) {
 
        NSUInteger  count = conver.unreadMessagesCount;
        self.unreadCounts = self.unreadCounts + count;
        
    }
    NSLog(@"++++++++++++++%ld",self.unreadCounts);
//发送通知
    NSString *unread = [NSString stringWithFormat:@"%ld",self.unreadCounts];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"unreadBadge" object:unread];
    
 
    
    
    
    
    
    
     [self.conversationTableView reloadData];
    
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.conversationArray.count;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ChatBaTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    
    
    EMConversation *conver = [self.conversationArray objectAtIndex:indexPath.row];
    
    cell.conversation = conver;
    return cell;
    
}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    EMConversation *conver = [self.conversationArray objectAtIndex:indexPath.row];
    [conver markAllMessagesAsRead:YES];
    ChattingViewController *chattingVC = [[ChattingViewController alloc]init];
    chattingVC.hidesBottomBarWhenPushed = YES;
    chattingVC.oppositeName = conver.chatter;
    [self.navigationController pushViewController:chattingVC animated:YES];
    [chattingVC release];
    
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 60;
    
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return YES;
}


-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return UITableViewCellEditingStyleDelete;
}




-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    EMConversation *conver = [self.conversationArray objectAtIndex:indexPath.row];
    
    [[EaseMob sharedInstance].chatManager removeConversationByChatter:conver.chatter deleteMessages:YES append2Chat:NO];
    
    [self.conversationArray removeObjectAtIndex:indexPath.row];
    
    [self.conversationTableView reloadData];
    
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




@end
